

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="银行家算法（Banker&#39;s Algorithm）是一个避免死锁（Deadlock）的著名算法，是由艾兹格·迪杰斯特拉在1965年为T.H.E系统设计的一种避免死锁产生的算法。它以银行借贷系统的分配策略为基础，判断并保证系统的安全运行。">
<meta property="og:type" content="article">
<meta property="og:title" content="银行家算法">
<meta property="og:url" content="https://cheney822.gitee.io/2021/05/01/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E9%93%B6%E8%A1%8C%E5%AE%B6%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="银行家算法（Banker&#39;s Algorithm）是一个避免死锁（Deadlock）的著名算法，是由艾兹格·迪杰斯特拉在1965年为T.H.E系统设计的一种避免死锁产生的算法。它以银行借贷系统的分配策略为基础，判断并保证系统的安全运行。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210520162538491-20220405205850848.jpeg">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210402093851127-20220405205850894.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210402103129995-20220405205850947.jpeg">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/2021040209394963-20220405205850996.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210403143636143-20220405205851056.png">
<meta property="article:published_time" content="2021-05-01T00:22:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:29.635Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="C语言">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/20210520162538491-20220405205850848.jpeg">
  
  
  <title>银行家算法 - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="银行家算法">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-05-01 08:22" pubdate>
        2021年5月1日 早上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.5k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      28 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">银行家算法</h1>
            
            <div class="markdown-body">
              <h1 id="银行家算法的实现"><a href="#银行家算法的实现" class="headerlink" title="银行家算法的实现"></a>银行家算法的实现</h1><p><em>以下部分内容来自百度百科：<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E9%93%B6%E8%A1%8C%E5%AE%B6%E7%AE%97%E6%B3%95">银行家算法</a></em></p>
<h4 id="题目描述："><a href="#题目描述：" class="headerlink" title="题目描述："></a>题目描述：</h4><ul>
<li>&emsp;&emsp;银行家算法（Banker’s Algorithm）是一个避免死锁（Deadlock）的著名算法，是由艾兹格·迪杰斯特拉在1965年为T.H.E系统设计的一种避免死锁产生的算法。它以银行借贷系统的分配策略为基础，判断并保证系统的安全运行。<br>&emsp;&emsp;在银行中，客户申请贷款的数量是有限的，每个客户在第一次申请贷款时要声明完成该项目所需的最大资金量，在满足所有贷款要求时，客户应及时归还。银行家在客户申请的贷款数量不超过自己拥有的最大值时，都应尽量满足客户的需要。在这样的描述中，银行家就好比操作系统，资金就是资源，客户就相当于要申请资源的进程。</li>
</ul>
<p>&emsp;&emsp;银行家算法是一种最有代表性的避免死锁的算法。在避免死锁方法中允许进程动态地申请资源，但系统在进行资源分配之前，应先计算此次分配资源的安全性，若分配不会导致系统进入不安全状态，则分配，否则等待。为实现银行家算法，系统必须设置若干数据结构。<br>&emsp;&emsp;操作系统安全状态和不安全状态,，等价于操作系统是否存在一个安全序列。安全序列是指一个进程序列{P1，…，Pn}是安全的，即对于每一个进程Pi(1≤i≤n），它以后尚需要的资源量不超过系统当前剩余资源量与所有进程Pj (j &lt; i )当前占有资源量之和。</p>
<p><strong>数据结构</strong><br>1）可利用资源向量Available<br>是个含有m个元素的数组，其中的每一个元素代表一类可利用的资源数目。如果Available[j]=K，则表示系统中现有Rj类资源K个。<br>2）最大需求矩阵Max<br>这是一个n×m的矩阵，它定义了系统中n个进程中的每一个进程对m类资源的最大需求。如果Max[i,j]=K，则表示进程i需要Rj类资源的最大数目为K。<br>3）分配矩阵Allocation<br>这也是一个n×m的矩阵，它定义了系统中每一类资源当前已分配给每一进程的资源数。如果Allocation[i,j]=K，则表示进程i当前已分得Rj类资源的 数目为K。<br>4）需求矩阵Need。<br>这也是一个n×m的矩阵，用以表示每一个进程尚需的各类资源数。如果Need[i,j]=K，则表示进程i还需要Rj类资源K个，方能完成其任务。<br>其中蕴含了关系：Need[i,j]=Max[i,j]-Allocation[i,j]，因此Need，Max，Allocation，三者只需要知道两个即可。<img src="https://imgbed.cheney.cc/picgo/20210520162538491-20220405205850848.jpeg" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>算法原理:</strong><br>&emsp;&emsp;我们可以把操作系统看作是银行家，操作系统管理的资源相当于银行家管理的资金，进程向操作系统请求分配资源相当于用户向银行家贷款。<br>为保证资金的安全，银行家规定：<br>(1) 当一个顾客对资金的最大需求量不超过银行家现有的资金时就可接纳该顾客；<br>(2) 顾客可以分期贷款，但贷款的总数不能超过最大需求量；<br>(3) 当银行家现有的资金不能满足顾客尚需的贷款数额时，对顾客的贷款可推迟支付，但总能使顾客在有限的时间里得到贷款；<br>(4) 当顾客得到所需的全部资金后，一定能在有限的时间里归还所有的资金.<br>操作系统按照银行家制定的规则为进程分配资源，当进程首次申请资源时，要测试该进程对资源的最大需求量，如果系统现存的资源可以满足它的最大需求量则按当前的申请量分配资源，否则就推迟分配。当进程在执行中继续申请资源时，先测试该进程本次申请的资源数是否超过了该资源所剩余的总量。若超过则拒绝分配资源，若能满足则按当前的申请量分配资源，否则也要推迟分配。</p>
<h5 id="算法实现："><a href="#算法实现：" class="headerlink" title="算法实现："></a>算法实现：</h5><h6 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h6><p>由用户输入数据，分别对可利用资源向量矩阵AVAILABLE、分配矩ALLOCATION、需求矩阵NEED赋值。</p>
<h6 id="具体过程："><a href="#具体过程：" class="headerlink" title="具体过程："></a>具体过程：</h6><p>银行家算法的基本思想是分配资源之前，判断系统是否是安全的；若是，才分配。它是最具有代表性的避免死锁的算法。在该方法中把系统的状态分为安全状态和不安全状态，只要能使系统始终都处于安全状态，便可以避免发生死锁。<br>设进程q提出请求REQUEST [i]，则银行家算法按如下规则进行判断。<br>(1)如果REQUEST [q] [i]&lt;= NEED[q][i]，则转(2)；否则，出错。<br>(2)如果REQUEST [q] [i]&lt;= AVAILABLE[i]，则转(3)；否则，等待。<br>(3)系统试探分配资源，修改相关数据：<br>AVAILABLE[i]-=REQUEST[q][i];<br>ALLOCATION[q][i]+=REQUEST[q][i];<br>NEED[q][i]-=REQUEST[q][i];<br>(4)系统执行安全性检查，如安全，则分配成立；否则试探险性分配作废，系统恢复原状，进程等待。<br><img src="https://imgbed.cheney.cc/picgo/20210402093851127-20220405205850894.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h6 id="安全性检查算法"><a href="#安全性检查算法" class="headerlink" title="安全性检查算法"></a>安全性检查算法</h6><p>(1)设置两个工作向量Work=AVAILABLE;FINISH<br>(2)从进程集合中找到一个满足下述条件的进程，<br>FINISH==false;<br>NEED&lt;=Work;<br>如找到，执行（3)；否则，执行（4)<br>(3)设进程获得资源，可顺利执行，直至完成，从而释放资源。<br>Work=Work+ALLOCATION;<br>Finish=true;<br>GOTO 2<br>(4)如所有的进程Finish= true，则表示安全；否则系统不安全。<br><img src="https://imgbed.cheney.cc/picgo/20210402103129995-20220405205850947.jpeg" srcset="/img/loading.gif" lazyload alt="来自王道考研"></p>
<h6 id="寻找安全序列时需要注意的问题："><a href="#寻找安全序列时需要注意的问题：" class="headerlink" title="寻找安全序列时需要注意的问题："></a>寻找安全序列时需要注意的问题：</h6><p>在安全检查中寻找符合条件的进程时，不能仅用一层循环来实现对所有进程的遍历，否则无法过滤错误的序列。<br>应该采用类似与DFS的方式遍历每一种可能的序列，不断的”试错“，找到错误的序列就主动回退寻找下一条序列。</p>
<h6 id="具体方法："><a href="#具体方法：" class="headerlink" title="具体方法："></a>具体方法：</h6><ol>
<li><p>每次从tem+1位置开始遍历，判断是否有符合条件（work&lt;need[p]且Finish[j] == 0）的进程p</p>
</li>
<li><p>如果有符合的进程就执行：</p>
</li>
</ol>
<ul>
<li><p>Finish[p] = 1;</p>
</li>
<li><p>Cstack.push(p);</p>
</li>
<li><p>Work[i] += Alloc[flag0][i] //进程释放资源</p>
</li>
<li><p>tem = 0;//有元素入栈后 tem=1 下次从头开始扫描</p>
<ol start="3">
<li>如果没有符合的进程并且进程已经全部进入安全序列则：</li>
</ol>
</li>
<li><p>return 1;//如果已经全部进入安全序列 返回1</p>
</li>
<li><p>返回对符合条件进程的判断步骤</p>
<ol start="4">
<li>如果没有符合的进程并且进程没有全部进入安全序列并且栈不空则：</li>
</ol>
</li>
<li><p>tem = Cstack.top();</p>
</li>
<li><p>Finish[tem] = 0;</p>
</li>
<li><p>Work[i] -= Alloc[tem][i];//回归进程释放资源</p>
</li>
<li><p>Cstack.pop();</p>
</li>
<li><p>返回对符合条件进程的判断步骤</p>
<ol start="5">
<li>如果没有符合的进程并且进程没有全部进入安全序列并且栈为空则：</li>
</ol>
</li>
<li><p>return 0;<br> <img src="https://imgbed.cheney.cc/picgo/2021040209394963-20220405205850996.png" srcset="/img/loading.gif" lazyload alt="银行家算法流程图："></p>
</li>
</ul>
<p>银行家算法的C++实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;iostream&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stack&gt;</span></span><br><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> std;<br><span class="hljs-meta">#<span class="hljs-keyword">define</span> n 5<span class="hljs-comment">//进程个数</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> m 3<span class="hljs-comment">//资源种类</span></span><br><span class="hljs-type">bool</span> Finish[n+<span class="hljs-number">1</span>];<span class="hljs-comment">//安全序列 </span><br>stack&lt;<span class="hljs-type">int</span>&gt; Cstack;<br><span class="hljs-comment">//int Available[m + 1], Alloc[n + 1][m + 1], Need[n + 1][m + 1];</span><br><span class="hljs-type">int</span> Available[m+<span class="hljs-number">1</span>] = &#123; <span class="hljs-number">0</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">3</span> &#125;;<br><span class="hljs-type">int</span> Alloc[n+<span class="hljs-number">1</span>][m+<span class="hljs-number">1</span>] = &#123;<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,     <span class="hljs-number">0</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,    <span class="hljs-number">0</span>,<span class="hljs-number">4</span>,<span class="hljs-number">0</span>,<span class="hljs-number">2</span>,   <span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">0</span>,<span class="hljs-number">5</span>,     <span class="hljs-number">0</span>,<span class="hljs-number">2</span>,<span class="hljs-number">0</span>,<span class="hljs-number">4</span>,   <span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">1</span>,<span class="hljs-number">4</span> &#125;;<br><span class="hljs-type">int</span> Need[n+<span class="hljs-number">1</span>][m+<span class="hljs-number">1</span>] = &#123; <span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,      <span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">7</span>,     <span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,     <span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">3</span>,    <span class="hljs-number">0</span>, <span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,     <span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">0</span>&#125;;<br><span class="hljs-comment">/*几组测试数据</span><br><span class="hljs-comment">2 0 3 4   无法满足，因为请求资源大于系统现有的资源数</span><br><span class="hljs-comment">4 1 0 1    4 2 3 5 1</span><br><span class="hljs-comment">1 2 0 1   安全检查无法满足，该进程被阻塞：</span><br><span class="hljs-comment">3 0 0 2    3 2 4 5 1  */</span><br><br><br><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">StackPrint</span><span class="hljs-params">(stack&lt;<span class="hljs-type">int</span>&gt; &amp;a)</span> </span>&#123; <span class="hljs-comment">// 用于递归的输出一个栈的信息</span><br>    <span class="hljs-keyword">if</span> (a.<span class="hljs-built_in">empty</span>())<br>        <span class="hljs-keyword">return</span>;<br>    <span class="hljs-type">int</span> A = a.<span class="hljs-built_in">top</span>();<br>    a.<span class="hljs-built_in">pop</span>();<br>    <span class="hljs-built_in">StackPrint</span>(a);<br>    cout &lt;&lt; A &lt;&lt; <span class="hljs-string">&quot;--&gt;&quot;</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">SafeCheck</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= n; i++)<br>        Finish[i] = <span class="hljs-number">0</span>;<span class="hljs-comment">//安全序列，0表示i号进程不在其中</span><br>    <span class="hljs-type">int</span> Work[m+<span class="hljs-number">1</span>];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++)<br>        Work[i] = Available[i];<br><br>    <span class="hljs-type">int</span> tem = <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-type">int</span> flag0 = <span class="hljs-number">0</span>;<span class="hljs-comment">//是否存在</span><br>        <span class="hljs-type">int</span> flag1;<span class="hljs-comment">//该进程work可满足（work&lt;need[p]）的p</span><br><br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = tem+<span class="hljs-number">1</span>; j &lt;= n; j++) &#123;<br>            flag1 = <span class="hljs-number">1</span>;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++)<br>                <span class="hljs-keyword">if</span> (Need[j][i] &gt; Work[i])<br>                    flag1 = <span class="hljs-number">0</span>;<br>            <span class="hljs-keyword">if</span> (Finish[j] == <span class="hljs-number">0</span> &amp;&amp; flag1 == <span class="hljs-number">1</span>) &#123;<br>                flag0 = j;<br>                <span class="hljs-keyword">break</span>;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (flag0 != <span class="hljs-number">0</span>) &#123;<br>            Finish[flag0] = <span class="hljs-number">1</span>;<span class="hljs-comment">//进程进入安全序列</span><br>            Cstack.<span class="hljs-built_in">push</span>(flag0);<br>            tem = <span class="hljs-number">0</span>;<span class="hljs-comment">//有元素入栈后 tem=1 下次从头开始扫描</span><br>            <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++)<br>                Work[i] += Alloc[flag0][i];<span class="hljs-comment">//进程释放资源</span><br>        &#125;<br>        <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-keyword">if</span> (Cstack.<span class="hljs-built_in">size</span>() == n)<br>                <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<span class="hljs-comment">//如果已经全部进入安全序列 返回1</span><br>            <span class="hljs-keyword">if</span> (!Cstack.<span class="hljs-built_in">empty</span>()) &#123;<br>                tem = Cstack.<span class="hljs-built_in">top</span>();<br>                Finish[tem] = <span class="hljs-number">0</span>;<br>                <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++)<br>                    Work[i] -= Alloc[tem][i];<span class="hljs-comment">//回归进程释放资源</span><br>                Cstack.<span class="hljs-built_in">pop</span>();<br>            &#125;<br>            <span class="hljs-keyword">else</span><br>                <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>        &#125;<br>    &#125;<span class="hljs-comment">// while结束</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-type">int</span> Request[m + <span class="hljs-number">1</span>];<span class="hljs-comment">//当前的请求</span><br>        <span class="hljs-type">int</span> p;<span class="hljs-comment">//当前是几号进程在请求资源;</span><br>        cout &lt;&lt; <span class="hljs-string">&quot;请输入当前请求资源的进程编号（-1可退出）： &quot;</span>;<br>        cin &gt;&gt; p;<br>        <span class="hljs-keyword">if</span> (p &gt; n) &#123;<br>            cout &lt;&lt; <span class="hljs-string">&quot;输入错误&quot;</span> &lt;&lt; endl;<br>            <span class="hljs-keyword">continue</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (p == <span class="hljs-number">-1</span>)  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<span class="hljs-comment">//输入-1 表示退出程序</span><br>        cout &lt;&lt; <span class="hljs-string">&quot;请输入当前进程请求资源的向量： &quot;</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++)<br>            cin &gt;&gt; Request[i];<br><br>        <span class="hljs-type">int</span> flag = <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++) <span class="hljs-comment">//检查Request &lt; Need 即请求是否合法（小于宣称的最大值）</span><br>            <span class="hljs-keyword">if</span> (Request[i] &gt; Need[p][i])<br>                flag = <span class="hljs-number">0</span>;<span class="hljs-comment">//不合法</span><br>        <span class="hljs-keyword">if</span> (flag == <span class="hljs-number">0</span>) &#123;<br>            cout &lt;&lt; <span class="hljs-string">&quot;不合法，因为请求资源大于宣称的最大资源&quot;</span> &lt;&lt; endl;<br>            <span class="hljs-keyword">continue</span>;<br>        &#125;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++) <span class="hljs-comment">//检查Request[i] &lt; Available[i] 即系统资源够不够当前用</span><br>            <span class="hljs-keyword">if</span> (Request[i] &gt; Available[i])<br>                flag = <span class="hljs-number">0</span>;<span class="hljs-comment">//无法满足</span><br>        <span class="hljs-keyword">if</span> (flag == <span class="hljs-number">0</span>) &#123;<br>            cout &lt;&lt; <span class="hljs-string">&quot;无法满足，因为请求资源大于系统现有的资源数&quot;</span> &lt;&lt; endl;<br>            <span class="hljs-keyword">continue</span>;<br>        &#125;<br>        <span class="hljs-comment">//程序执行到此表示已经通过上述安全检查，可以试探性的把资源分配给该进程：</span><br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++) &#123;<br>            Available[i] -= Request[i];<br>            Alloc[p][i] += Request[i];<br>            Need[p][i] -= Request[i];<br>        &#125;<br>        <span class="hljs-comment">//分配资源后，执行安全性算法检查</span><br>        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">SafeCheck</span>()) &#123;<br>            cout &lt;&lt; <span class="hljs-string">&quot;安全检查可以满足，安全序列为：&quot;</span> &lt;&lt; endl;<br>            <span class="hljs-built_in">StackPrint</span>(Cstack);<br>        &#125;<br>        <span class="hljs-keyword">else</span><br>            cout &lt;&lt; <span class="hljs-string">&quot;安全检查无法满足，该进程被阻塞：&quot;</span> &lt;&lt; endl;<br><br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= m; i++) &#123;<br>            Available[i] += Request[i];<br>            Alloc[p][i] -= Request[i];<br>            Need[p][i] += Request[i];<br>        &#125;<br>    &#125;<span class="hljs-comment">//主循环</span><br>&#125;<br><br></code></pre></td></tr></table></figure>

<h3 id="运行结果："><a href="#运行结果：" class="headerlink" title="运行结果："></a>运行结果：</h3><h6 id="根据题目要求，输入四组测试数据进行测试，得到的结果如下图："><a href="#根据题目要求，输入四组测试数据进行测试，得到的结果如下图：" class="headerlink" title="根据题目要求，输入四组测试数据进行测试，得到的结果如下图："></a>根据题目要求，输入四组测试数据进行测试，得到的结果如下图：</h6><p><img src="https://imgbed.cheney.cc/picgo/20210403143636143-20220405205851056.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h6 id="测试数据及结果整理到表格内可得："><a href="#测试数据及结果整理到表格内可得：" class="headerlink" title="测试数据及结果整理到表格内可得："></a>测试数据及结果整理到表格内可得：</h6><table>
<thead>
<tr>
<th>编号</th>
<th>进程号</th>
<th>申请的资源</th>
<th>输出结果：</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>2</td>
<td>0，3，4</td>
<td>无法满足，因为请求资源大于系统现有的资源数</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>1，0，1</td>
<td>4 2 3 5 1</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>2，0，1</td>
<td>安全检查无法满足，该进程被阻塞：</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>0，0，2</td>
<td>3 2 4 5 1</td>
</tr>
</tbody></table>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E7%AE%97%E6%B3%95/">算法</a>
                    
                      <a class="hover-with-bg" href="/tags/C%E8%AF%AD%E8%A8%80/">C语言</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/05/02/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E5%8A%A8%E6%80%81%E5%88%86%E5%8C%BA%E5%BC%8F%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">动态分区式内存管理</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/20/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86__%E5%9F%BA%E4%BA%8EDFA%E7%9A%84%E8%AF%8D%E6%B3%95%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9A%E6%9E%84%E9%80%A0DFA/">
                        <span class="hidden-mobile">基于DFA的词法分析（二）：构造DFA</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
